import {StatusBar, NativeModules, NativeEventEmitter, EmitterSubscription} from "react-native";
import Toast, {ToastType, ToastShowParams} from 'react-native-toast-message';
import {channelMaps} from "@/theme/enums/screen";
import config from "@/config";
import {toUpperCase} from "@/utils/modules/format";

export function getChannel(v: number, reversal = 0) {
    return toUpperCase(channelMaps[v], reversal);
}

interface ToastParams extends ToastShowParams {
    callBack: () => any
}

const {OS, uiWidthPx, deviceWidthDp} = config;

//  转换 px 为 dp
export function pxToDp(uiElementPx: number) {
    return (uiElementPx * deviceWidthDp) / uiWidthPx;
}

// 获取状态栏高度
export function getStatusHeight() {
    const {StatusBarManager} = NativeModules;
    return OS === "ios" ? StatusBarManager.HEIGHT : (StatusBarManager && StatusBarManager.HEIGHT) || StatusBar.currentHeight;
}

// 获取设备语言
export const getDeviceLanguage = (): string => {
    let deviceLanguage;

    if (OS === 'android') {
        // 获取 Android 设备语言
        deviceLanguage =
            NativeModules.I18nManager.localeIdentifier ||
            NativeModules.I18nManager.localeIdentifier.slice(0, 2);
    } else {
        // 获取 iOS 设备语言
        deviceLanguage =
            NativeModules.SettingsManager.settings.AppleLocale ||
            NativeModules.SettingsManager.settings.AppleLanguages[0];
    }

    return deviceLanguage.toLowerCase();
};

// 语言变化监听
export function languageListener(call: (locale: string) => void) {
    let localeEmitter = new NativeEventEmitter(NativeModules.RCTDeviceInfo);

    let localeChangeListener: EmitterSubscription;
    if (OS == "ios") {
        localeChangeListener = localeEmitter.addListener(
            'RCTDeviceLocale',
            (locale) => {
                // 处理本机语言变化
                console.log(`本机语言已更改为：${locale}`);
                call(locale);
            }
        );
    } else {
        localeChangeListener = localeEmitter.addListener(
            'RCTDeviceLocaleDidChange',
            (locale) => {
                // 处理本机语言变化
                console.log(`本机语言已更改为：${locale}`);
                call(locale);
            }
        );
    }
    return localeChangeListener;
}

export function showToast(text1: string, type: ToastType = "success", options?: ToastParams) {
    let visibilityTime = 1500;
    Toast.show({
        type,
        text1,
        visibilityTime,
        onShow: () => {
            options?.callBack && setTimeout(options.callBack, visibilityTime);
        },
        ...options
    });
}

export function hideToast() {
    Toast.hide();
}
